﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GCTrackableRace.Interfaces;
using GcTrackableRace.Entities;

namespace GcTrackableRace.ScoreCalculator.Rules
{
	public class CitoCacheVisitRule : BaseRule, IRaceRule
	{
		public CitoCacheVisitRule(string reportColumnName, string startDate, string endDate, string pointAllocation, IGeocacheInfo geocacheInfo)
			: base(reportColumnName, startDate, endDate, pointAllocation)
		{
			GeocacheInfo = geocacheInfo;
		}

		private IGeocacheInfo GeocacheInfo { get; set; }

		protected override void SetRuleName()
		{
			RuleName = "Cito cache visit rule";
		}

		public override void Process(ITrackable trackable, IEnumerable<ITrackableLog> trackableLogs)
		{
			var allDroppedAndVisitedLogs = (
				from log in trackableLogs
				where (
					(log.LogType == LogType.DroppedOff || log.LogType == LogType.Visited)
					&&
						(
							log.Date >= StartDate
							&&
							log.Date <= EndDate
						)
					)
				select log)
				.OrderBy(logs => logs.Date)
				.ThenBy(logs => logs.LogId)
				.ToList();

			var citoCaches = (
				from log in allDroppedAndVisitedLogs
				let geocache = GeocacheInfo.GetDetail(log.LocationGcCode)
				where geocache != null && geocache.IsCitoCache
				select log.LocationGcCode)
				.ToList();

			trackable.AddScore(new RuleScore(
				RuleName, 
				ReportColumnName,
				citoCaches.Count,
				(int)(citoCaches.Count * PointAllocation),
				String.Join("|", citoCaches).Trim('|')));
		}
	}
}
